<?php

namespace App\Http\Controllers\Admin;

use App\Tag;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class TagController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $tags = Tag::all();
        return view('admin.tag.index', ['tags'=>$tags, 'request'=>$request]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.tag.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
        $input['date'] = time();
        //验证
        $this->validate($request, [
            'name' => 'required|unique:tags'
        ],[
            'name.required' => '标签名不能为空',
            'name.unique' => '标签名不能重复'
        ]);
        if(Tag::create($input)){
            return redirect('admin/tag')->with('info', '标签添加成功');
        }else{
            return back()->with('info', '标签添加失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $tag = Tag::findOrFail($id);
        return view('admin.tag.edit', ['tag'=>$tag]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $tag = Tag::findOrFail($id);
        $tag->name = $request->input('name');
        //验证
        $this->validate($request, [
            'name' => 'required|unique:tags'
        ],[
            'name.required' => '标签名不能为空',
            'name.unique' => '标签名不能重复'
        ]);
        if($tag->save()){
            return redirect('admin/tag')->with('info', '标签更新成功');
        }else{
            return back()->with('info', '标签更新失败');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $tag = Tag::findOrFail($id);
        if($tag->delete()){
            return redirect('admin/tag')->with('info', '标签删除成功');
        }else{
            return back()->with('info', '标签删除失败');
        }
    }
}
